package com.teacher.pc.controller;


import com.teacher.common.CommonResult;
import com.teacher.common.utils.FileNameUtil;
import com.teacher.common.utils.FileUploadUtil;
import com.teacher.common.utils.ImageSuffix;
import com.teacher.pojo.dto.file.FileAddDto;
import com.teacher.pojo.vo.FileViewVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 系统文件 前端控制器
 * </p>
 *
 * @author zfm
 * @since 2020-12-16
 */
@RestController
@RequestMapping("/basic/sys-file-log")
public class SysFileLogController {

    @Autowired
    private ImageSuffix imageSuffix;

    @Value("${web.files}")
    private String localPath;

    @Value("${web.attachments}")
    private String mappingAttachmentsPath;

    @Value("${web.images}")
    private String mappingImagePath;

    private static final String ROOTPATH = "";

    @PostMapping("/upload")
    @ApiOperation("图片上传")
    public CommonResult upload(@RequestParam(name = "file") MultipartFile file) {
        FileViewVo fileViewVo = null;
        if (file == null) {
            return null;
        }
        //获取新文件名
        String fileName = "";
        String oriName = file.getOriginalFilename();
        fileName = FileNameUtil.getFileName(oriName);
        //拼接文件路径，上传到服务器
        if (FileUploadUtil.upload(file, localPath + mappingImagePath, fileName)) {
            fileViewVo = new FileViewVo();
            //拼接图片映射路径
            fileViewVo.setUrl(ROOTPATH + mappingImagePath + fileName);
        }
        if (fileViewVo != null) {
            Map<String, Object> data = new HashMap<>();
            Map<String, Object> img = new HashMap<>();
            img.put("url", fileViewVo.getUrl());
            img.put("name", oriName);
            data.put("data", img);
            return CommonResult.success(data);
        }
        return CommonResult.failed("上传失败");
    }

    @PostMapping("/uploadFile")
    @ApiOperation("文件上传")
    public CommonResult uploadFile(@RequestParam(name = "file") MultipartFile file) {

        Map<String, Object> map = new HashMap<>();
        if (file == null) {
            return null;
        }

        String fileName = file.getOriginalFilename();
        map.put("name", fileName);
        fileName = FileNameUtil.getFileName(fileName);
        //拼接文件路径，上传到服务器
        if (FileUploadUtil.upload(file, localPath + mappingAttachmentsPath, fileName)) {
            //拼接图片映射路径
            map.put("url", ROOTPATH + mappingAttachmentsPath + fileName);
        }
        if (map.get("name") != null) {
            Map<String, Object> mapEnd = new HashMap<>();
            mapEnd.put("data", map);
            return CommonResult.success(map);
        }
        return CommonResult.failed("上传失败");
    }

}

